package Test;
import Utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import java.io.*;import java.net.*;import java.util.ArrayList;import java.util.List;
public class Server {
    public static SqlSession sqlSession = MybatisUtils.getSqlSession();
    public static UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
    private static final int PORT = 3915;
    private static final List<ClientHandler> clients = new ArrayList<>();
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("服务器正在监听端口 " + PORT);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接受来自客户端的连接: " + clientSocket.getInetAddress());
                // 创建客户端处理线程
                ClientHandler clientHandler = new ClientHandler(clientSocket);
                clients.add(clientHandler);
                Thread clientThread = new Thread(clientHandler);
                clientThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }// 客户端处理线程
    private static class ClientHandler implements Runnable {
        private Socket clientSocket;
        private BufferedReader reader;
        private PrintWriter writer;
        public ClientHandler(Socket clientSocket) {
            try {
                this.clientSocket = clientSocket;
                this.reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
                this.writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run(){
            try {
                String inputLine;
                while ((inputLine = reader.readLine()) != null) {
                    System.out.println("从客户端接收(" + clientSocket.getInetAddress() + "): " + inputLine);
                    // 分割消息
                    if (inputLine.contains("@")) {
                        String[] parts = inputLine.split("@", 2);
                        if (parts.length == 2) {
                            String targetIP = parts[0];
                            String message = parts[1];
                            sendMessageToTargetIP(targetIP, message);
                        }
                    } else {
                        broadcastMessage(inputLine);
                    }
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接: " + clientSocket.getInetAddress());
            } finally {
                clients.remove(this);
            }
        }
        // 向指定IP地址的客户端发送消息
        private void sendMessageToTargetIP(String targetIP, String message) {
            for (ClientHandler client : clients) {
                if (client.clientSocket.getInetAddress().getHostAddress().equals(targetIP)) {
                    client.writer.println(clientSocket.getInetAddress()  + message);
                    break; // 找到目标IP对应的客户端后即停止循环
                }
            }
        }
        //从数据库中获取IP地址
        public void sendMessageToTargetIPGetIPFromDatabase(String nickname, String message) {
            for (ClientHandler client : clients) {
                if (client.clientSocket.getInetAddress().getHostAddress().equals(usermapper.GetUserIPByNickname(nickname))) {
                    client.writer.println("私信(" + clientSocket.getInetAddress() + "): " + message);
                    break; // 找到目标IP对应的客户端后即停止循环
                }
            }
        }
        // 向所有客户端广播消息
        private void broadcastMessage(String message) {
            for (ClientHandler client : clients) {
                // 不向当前客户端发送消息
                if (client != this) {
                    client.writer.println("群消息(" + clientSocket.getInetAddress() + "): " + message);
                }
            }
        }
    }
}
